package com.starblink.wishlist.wishallitems.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.toastWishlist
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectWishListEvent
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.wishlist.databinding.FragmentWishAllItemsBinding
import com.starblink.wishlist.wishallitems.ui.bean.RvNormalEmpty
import com.starblink.wishlist.wishallitems.ui.bean.RvTotalNumEntry
import com.starblink.wishlist.wishallitems.ui.part.WishAllItemsPart
import com.starblink.wishlist.wishallitems.ui.part.WishFilterPart
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry

/**
 *
 */
class WishAllItemsFragment : BaseTVMFragment<FragmentWishAllItemsBinding, WishAllItemsVM>() {

    companion object {
        private const val TAG = "WishAllItemsFragment"

        //0 默认是首页心愿单 | 1 搜索界面复用
        private var displayType = 0


        fun obtainFragment(displayType: Int = 0): WishAllItemsFragment {
            this.displayType = displayType
            return WishAllItemsFragment()
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentWishAllItemsBinding {
        return FragmentWishAllItemsBinding.inflate(inflater, container, false)
    }

    lateinit var allItemsPart: WishAllItemsPart
    lateinit var filterPart: WishFilterPart

    /**
     * 初始化数据
     */
    override fun initData() {

        viewModel.displayType = displayType
        viewModel.initSomeData()
        allItemsPart = WishAllItemsPart(
            refreshStateView = viewBinding.page,
            recyclerView = viewBinding.rv,
            mActivity,
            viewBinding,
            viewModel
        ).apply {
            handleVM()
        }
        filterPart = WishFilterPart(mActivity, viewBinding, viewModel).apply {
            handleVM()
        }

        when (displayType) {
            0 -> {
//                viewBinding.page.margin(bottomMargin = 55.dp)
//            android:layout_marginBottom="55dp"
                //刷新 不绑定state 单独处理
                viewBinding.state.refreshing()
                viewBinding.page.onMutRefresh {
                    refreshMainData()
                }.refresh()
                viewBinding.page.onMutLoadMore {
                    if (viewModel.canLoadGuessData(false)) {
                        viewModel.loadMoreGuess(hasFinish = {
                            viewBinding.page.finishLoadMore()
                        }, activity = mActivity)
                    } else {
                        viewModel.loadMoreData(
                            hasFinish = {
                                viewBinding.page.finishLoadMore()
                            }, activity = mActivity
                        )
                    }
                }
            }

            1 -> {
                viewBinding.page.onMutRefresh {
                    refreshMainData()
                }
                viewBinding.page.onMutLoadMore {
                    viewModel.loadMoreData(
                        hasFinish = {
                            viewBinding.page.finishLoadMore()
                        }, activity = mActivity
                    )
                }
            }
        }

    }

    fun setSearchTitleKey(title: String?) {
        viewModel.searchTitleKey = title
    }

    //切换多选模式
    fun intoMutiSelect(choiceMode_1: Boolean) {
        allItemsPart.mutiChange(choiceMode_1)
    }

    fun hideBtmLay() {
        viewModel.choiceMode = false
        viewBinding.llMutiBtmLay.gone()
    }

    /**
     * 蛋疼的判断 目前存在最多4个选项 至少2个选项
     */
    fun refreshMainData(showSimpleDialog: Boolean = false) {
        when (displayType) {
            0 -> {
//                if (showSimpleDialog) {
//                viewBinding.state.refreshing()
//                }
                if (!UserDataCenter.isLogin() && !showSimpleDialog) {
                    viewModel.autoLoadMore = false
                    viewModel.statusParams = null
                    viewModel.timeParams = null
                    viewModel.hotBrandParams = null
                    viewModel.categoryParams = null
                    refreshAll(needFilter = false)
                } else {
                    //没有筛选项
                    //(viewModel.mFilterDataObserver.value!!.size>2 有类目筛选
                    //(viewModel.mFilterDataObserver.value!!.size>3 有品牌筛选
                    if (viewModel.statusParams == null && viewModel.timeParams == null) {
                        if (viewModel.mFilterDataObserver.value!!.size == 3) {
                            if (viewModel.categoryParams == null) {
                                refreshAll(showDialog = showSimpleDialog)
                            } else {
                                refreshFilter(showDialog = showSimpleDialog)
                            }
                        } else if (viewModel.mFilterDataObserver.value!!.size == 4) {
                            if (viewModel.hotBrandParams == null && viewModel.categoryParams == null) {
                                refreshAll(showDialog = showSimpleDialog)
                            } else {
                                refreshFilter(showDialog = showSimpleDialog)
                            }
                        } else {
                            refreshAll(showDialog = showSimpleDialog)
                        }
                    } else {
                        refreshFilter(showDialog = showSimpleDialog)
                    }
                }
            }

            1 -> {
                refreshFilter(showSimpleDialog)
            }
        }


    }

    private fun refreshAll(showDialog: Boolean = false, needFilter: Boolean = true) {
        viewModel.refreshData(showDialog = showDialog, needFilter = needFilter, hasFinish = {
            viewBinding.page.finishRefresh()
            viewBinding.state.showContent()
            if (viewModel.mAllItemsObserver.value!!.size == 0) {
                viewBinding.tabLayoutContent.gone()
            } else {
                if (displayType == 0) {
                    if (viewModel.mAllItemsObserver.value!!.size > 0) {
                        if (viewModel.mAllItemsObserver.value!![0] is RvNormalEmpty) {
                            viewBinding.tabLayoutContent.gone()
                        } else {
                            viewBinding.tabLayoutContent.visible()
                        }
                    } else {
                        viewBinding.tabLayoutContent.gone()
                    }
                } else {
                    viewBinding.tabLayoutContent.gone()
                }
            }
            //是否开启加载更多
//            if (viewModel.autoLoadMore) {
//                viewBinding.page.setEnableLoadMore(true)
//            } else {
//                viewBinding.page.setEnableLoadMore(false)
//            }
        }, activity = mActivity)
    }

    private fun refreshFilter(showDialog: Boolean = false) {
        YYLogUtils.e("------------------------刷筛选")
        viewModel.refreshFilterData(showDialog = showDialog, hasFinish = {
            viewBinding.page.finishRefresh()
            viewBinding.state.showContent()
            //是否开启加载更多
//            if (viewModel.autoLoadMore) {
//                viewBinding.page.setEnableLoadMore(true)
//            } else {
//                viewBinding.page.setEnableLoadMore(false)
//            }
        }, activity = mActivity)
    }


    var mustBeRefresh = false

    override fun onResume() {
        super.onResume()
        canRefresh()
    }

    fun canRefresh() {
        if (mustBeRefresh) {
            mustBeRefresh = false
            refreshMainData(
                showSimpleDialog = (viewModel.currentPageIndex == 0 && UserDataCenter.currentIndex == 2)
            )
//            refreshMainData(this.isVisible)
        }
    }

//    fun otherRefresh() {
//        if (mustBeRefresh) {
//            mustBeRefresh = false
//            refreshMainData(showSimpleDialog = (viewModel.currentPageIndex == 0))
//        }
//    }


    fun syncPageSelectIndex(pageIndex: Int) {
        viewModel.currentPageIndex = pageIndex
    }

    override fun startObserve() {
        //退出登录
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.autoLoadMore = false
            viewModel.statusParams = null
            viewModel.timeParams = null
            viewModel.hotBrandParams = null
            viewModel.categoryParams = null
            viewModel.mFilterDataObserver.value?.clear()
            mustBeRefresh = true
        }
        FlowBus.with<Boolean>(FlowConst.WISH_ALL_ITEMS_SCROLL_TOP).register(this) {
            viewBinding.rv.scrollToPosition(0)
        }
        FlowBus.with<CollectWishListEvent>(FlowConst.COLLECT_WISHLIST_EVENT).register(this) {
            mustBeRefresh = true
        }
        FlowBus.with<ProductF>(FlowConst.WISHLIST_ADD_PRODUCT_VIEW).register(this) {
            mustBeRefresh = true
        }
        FlowBus.with<Boolean>(FlowConst.OTHER_ADD_PRODUCT_VIEW).register(this) {
            mustBeRefresh = true
        }

        //下边的滚动判断和这个是绑在一起用的----->WISHLIST_ADD_PRODUCT_VIEW
        viewBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
//                if (!viewBinding.rv.canScrollVertically(1)) {
//                    //滑动到底部
//                }
                if (!viewBinding.rv.canScrollVertically(-1)) {
                    //滑动到顶部
                    if (mustBeRefresh && this@WishAllItemsFragment.isVisible) {
                        refreshMainData(showSimpleDialog = true)
                        mustBeRefresh = false
                    }
                }
            }
        })

        //显示删除弹窗
        FlowBus.with<Int>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_1).register(this) { removedItemNum ->
//            viewBinding.llMutiAddSuccessToast.visible()
//            viewBinding.llMutiAddSuccessToastTxt.text = "Removed successfully"
//            FlowCountDownTimer(time = 2).start(callBack = {
//            }, onFinish = {
//                viewBinding.llMutiAddSuccessToast.gone()
//            })
            toastWishlist("Removed successfully")
            if (viewModel.getCurrentItemDataSize() == 0) {
                refreshMainData(showSimpleDialog = true)
            }
        }

        //显示添加心愿单弹窗
        FlowBus.with<String>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_2).register(this) {
//            viewBinding.llMutiAddSuccessToast.visible()
//            viewBinding.llMutiAddSuccessToastTxt.buildSpannableString {
//                addText("Successfully added to") {
//                    setColor(Color.parseColor("#FFFFFF"))
//                }
//                addText(" $it ") {
//                    setColor(Color.parseColor("#FFFFFF"))
//                    setTypeface(Typeface.DEFAULT_BOLD)
//                }
//                addText("Board") {
//                    setColor(Color.parseColor("#FFFFFF"))
//                }
//            }
//            FlowCountDownTimer(time = 2).start(callBack = {
//            }, onFinish = {
//                viewBinding.llMutiAddSuccessToast.gone()
//            })

            toastWishlist("Successfully added to $it Board")

        }

        viewModel.mAllItemsObserver.observe(this) {
            showOrHideSetting(it)
        }

        viewModel.mFilterDataObserver.observe(this) {
            filterPart.refreshTabView(it)
        }
    }

    private fun showOrHideSetting(arr: ArrayList<Any>) {
        var num = 0
        arr.forEach { item ->
            if (item is RvBoardDetailsItemEntry) {
                num++
            }
        }
        var noData = false
        if (num == 0 && arr.size > 0 && arr[0] is RvTotalNumEntry) {
            arr.removeAt(0)
            arr.add(0, RvNormalEmpty())
            noData = true
        }
        if (num > 0 && arr[0] is RvNormalEmpty) {
            arr.removeAt(0)
            viewModel.lastFeedsSize -= 1
            noData = false
        }

        mDataChangeListener?.invoke(num, viewModel.selectAll, noData)
        allItemsPart.dataChange(arr)
    }

    private var mDataChangeListener: ((Int, Boolean, Boolean) -> Unit)? = null

    //
    fun setDataChangeListener(listener: (Int, Boolean, Boolean) -> Unit) {
        this.mDataChangeListener = listener
    }

    fun showFillView(show: Boolean) {
        viewBinding.fillView.visibleOrGone(show)
    }

}